package org.keyroy.tag;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Vector;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XmlSAX {

	public static Tag parseTag(InputStream inputStream) {
		final Tag root = new Tag();
		try {
			final Vector<Tag> tags = new Vector<Tag>();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new DefaultHandler() {
				private Tag currentTag;

				@Override
				public void startElement(String uri, String localName, String qName, Attributes attributes)
						throws SAXException {
					if (currentTag == null) {
						currentTag = root;
					} else {
						Tag tag = new Tag();
						currentTag.addChild(tag);
						currentTag = tag;
					}
					tags.add(currentTag);

					currentTag.setName(qName);

					for (int i = 0; i < attributes.getLength(); i++) {
						String name = attributes.getQName(i);
						String value = attributes.getValue(i);
						currentTag.addParameter(name, value);
					}
				}

				@Override
				public void endElement(String uri, String localName, String qName) throws SAXException {
					tags.removeElementAt(tags.size() - 1);
					if (tags.size() > 0) {
						currentTag = tags.lastElement();
					}
				}

				@Override
				public void characters(char[] ch, int start, int length) throws SAXException {
					currentTag.setText(new String(ch, start, length));
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return root;
	}

	public static Tag parseTag(String string) {
		try {
			return parseTag(new ByteArrayInputStream(string.getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(string);
		}
		return null;
	}
}
